//
// Created by Administrator on 2020/1/14.
//

#include <dlfcn.h>
#include "entry_hooks.h"
#include "log_utils.h"
#include "Hook.h"
#include "module_manager.h"

#define LOG_TAG "EntryHooks"

#define CREATE_JVM_NAME "JNI_CreateJavaVM"

jint my_create_jvm(JavaVM** p_vm, JNIEnv** p_env, void* reserved){
    void* old_func_ptr= Hook::GetInstance()->GetOldFunction(CREATE_JVM_NAME);
    if(!old_func_ptr){
        AKLogErr("fail to get old_function of name:%s\n",CREATE_JVM_NAME);
        return JNI_OK;
    }
    func_on_create_vm old_create_vm= reinterpret_cast<func_on_create_vm>(old_func_ptr);
    jint ret=old_create_vm(p_vm,p_env,reserved);
    AKLog("JNI_CreateJavaVM ret:%d\n",ret);
    //分发jvm事件
    std::map<std::string,Module*> moduleMap= ModuleManager::GetInstance()->mModuleMap;
    for(auto itor=moduleMap.begin();itor!=moduleMap.end(); itor++){
        Module* module= itor->second;
        module->mOnCreateVM(p_vm,p_env,reserved);
        AKLog("handled OnCreateVM:%p for module:%s\n",module->mOnCreateVM,module->mName.c_str());
    }
    return ret;
}

bool hook_create_jvm() {
    void* symbol=dlsym(RTLD_DEFAULT,"JNI_CreateJavaVM");
    if(!symbol){
        AKTagLogErr("fail to find JNI_CreateJavaVM symbol\n");
        return false;
    }
    Hook::GetInstance()->NativeHook(CREATE_JVM_NAME,symbol, reinterpret_cast<void*>(my_create_jvm));
    void* old_func= Hook::GetInstance()->GetOldFunction(CREATE_JVM_NAME);
    AKLog("old_func:%p\n",old_func);
    return old_func!= nullptr;
}
